import type { PluginOption } from 'vite';
import { dateUtil } from '../../node-utils';
import pkg from '../../../../package.json';
/**
 * 用于注入项目信息
 */
async function viteMetadataPlugin(): Promise<PluginOption | undefined> {
  const { author, description, homepage, license, version } = pkg as any;

  const buildTime = dateUtil().format('YYYY-MM-DD HH:mm:ss');

  return {
    async config() {
      const isAuthorObject = typeof author === 'object';
      const authorName = isAuthorObject ? author.name : author;
      const authorEmail = isAuthorObject ? author.email : null;
      const authorUrl = isAuthorObject ? author.url : null;

      return {
        define: {
          __BASIC_ADMIN_METADATA__: JSON.stringify({
            authorEmail,
            authorName,
            authorUrl,
            buildTime,
            description,
            homepage,
            license,
            version,
          }),
          'import.meta.env.VITE_APP_VERSION': JSON.stringify(version),
        },
      };
    },
    enforce: 'post',
    name: 'vite:inject-metadata',
  };
}

export { viteMetadataPlugin };
